package com.example.admin.smstest.sms;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.SmsMessage;

import com.example.admin.smstest.ConnectionManager;
import com.example.admin.smstest.utils.ByteUtil;
import com.example.admin.smstest.utils.CrcOperateUtil;
import com.example.admin.smstest.utils.DataUtil;
import com.example.admin.smstest.utils.DateUtil;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import static com.example.admin.smstest.utils.ByteUtil.hexStringToBytes;

/**
 * Created by yangjx on 2017/3/24.
 */

public class ReceiveSmsReciver extends BroadcastReceiver {
    private ConnectionManager mConnectionManager;//链接监听类
    private Context context;
    private SmsObserver smsObserver;
    private Uri SMS_INBOX = Uri.parse("content://sms/");
    @Override
    public void onReceive(Context context, Intent intent) {
        this.context = context;
      //  mConnectionManager = new ConnectionManager(mConnectionListener);
      //  mConnectionManager.startListen();
       // context.getContentResolver().registerContentObserver(SMS_INBOX, true, new SmsObserver(new Handler()));

        Bundle bundle = intent.getExtras();
        if (bundle != null) {
            Object[] smsObj = (Object[]) bundle.get("pdus");
            SmsMessage msg = null;
            for (Object object : smsObj) {
                msg = SmsMessage.createFromPdu((byte[]) object);
                String date = String.valueOf(msg.getTimestampMillis());//时间
                String body = msg.getMessageBody();
                String address = msg.getOriginatingAddress();
                String address1 = msg.getDisplayOriginatingAddress();
                System.out.println(address + "====" +address1);
                System.out.println(body);
//                try {
//                    sendMessage(date,address,body);
//                } catch (UnsupportedEncodingException e) {
//                    e.printStackTrace();
//                }
            }
        }
    }

    /**
     * 链接监听
     */
    private ConnectionManager.ConnectionListener mConnectionListener = new ConnectionManager.ConnectionListener() {

        @Override
        public void onConnectStateChange(int oldState, int State) {
        }

        @Override
        public void onListenStateChange(int oldState, int State) {
        }

        @Override
        public void onSendData(boolean suc, byte[] data) throws UnsupportedEncodingException {
            System.out.println("发送监听："+ Arrays.toString(data));
            //getData(data);
        }

        @Override
        public void onReadData(byte[] data) {
            //System.out.println("接收："+Arrays.toString(data));
            //getData(data);
        }
    };

    /**
     * 发送短信数据
     * @param date
     * @param numbers
     * @param body
     * @throws UnsupportedEncodingException
     */
    private void sendMessage(String date,String numbers,String body) throws UnsupportedEncodingException{
        System.out.println("send =========================================");
        String id = "999";
        String type = "1";
        // 1.帧头
        byte[] frameHeader = DataUtil.MAGICTYPES;
        // 2.作用域
        byte[] function = DataUtil.FUNCTION;
        //                   序列号|业务号|操作类型 (type)| Type(TLV)
        byte[] baowentou = {  0x01,  0x05,        0x03,        0x01};// 10B

        // value的长度
        // a.时间
        byte[] timeB = hexStringToBytes(date);
        // b.destination  1==接受 2==发送
        byte[] destinationB = ByteUtil.intToHexBytes(Integer.parseInt(type));
        // c.Short message ID number
        int idI = Integer.parseInt(id,10);
        byte[] idB = ByteUtil.intToHexBytes(idI);
        // d.number 短信的电话号码
        byte[] numberB = ByteUtil.getByte(numbers);
        // e.获取当前的短信内容

        byte[] smsValueB = null;

        int total = body.length()/100 + 1;
        //总包数totalB为真实值
        byte[] totalB = ByteUtil.getPackets(total);
        //   for(int i = 0;i < total ;i++){
        //      System.out.println("一共几个包"+total);
//            if(i != total -1){
//                //当前报数
//                byte[] totalC = ByteUtil.getPackets(i+1);
//                String body1 = body.substring(i*100,(i+1)*100);
//                byte[] bodyByte= ByteUtil.getByte(body1);
//                // TLV中的Value
//                smsValueB = ByteUtil.concatAll(timeB,destinationB,idB,numberB,bodyByte);
//                // 3.短信长度
//                byte[] smsByteLength = ByteUtil.intToHexBytes(smsValueB.length);
//                // 4.TLV长度
//                byte[] valueTotalLength = ByteUtil.intToHexBytes(smsValueB.length+7);
//                // 加crc校验
//                byte[] andData = ByteUtil
//                        .concatAll(function,valueTotalLength ,totalB,totalC,baowentou,smsByteLength,smsValueB);
//                byte[] endData = CrcOperateUtil.setParamCRC(andData);
//
//                byte[] data = ByteUtil.concatAll(frameHeader, endData);
//                System.out.println("长度=="+data.length);
//                System.out.println(Arrays.toString(data));
//                boolean sendSuccess = mConnectionManager.sendData(data);
//                System.out.println("发送成功？"+sendSuccess);
//            }else if(i == (total - 1)){
        //当前报数，最后一个包名
//                byte[] totalC = ByteUtil.getPackets(i+1);
//                String body1 = body.substring(i*100,body.length());
//                byte[] bodyByte= ByteUtil.getByte(body1);
        byte[] totalC = ByteUtil.getPackets(1);
        String body1 = body.substring(0,body.length());
        byte[] bodyByte= ByteUtil.getByte(body);
        // TLV中的Value
        smsValueB = ByteUtil.concatAll(timeB,destinationB,idB,numberB,bodyByte);
        // 3.短信长度
        byte[] smsByteLength = ByteUtil.intToHexBytes(smsValueB.length);
        // 4.TLV长度
        byte[] valueTotalLength = ByteUtil.intToHexBytes(smsValueB.length+7);
        // 加crc校验
        byte[] andData = ByteUtil
                .concatAll(function,valueTotalLength ,totalB,totalC,baowentou,smsByteLength,smsValueB);
        byte[] endData = CrcOperateUtil.setParamCRC(andData);
        byte[] data = ByteUtil.concatAll(frameHeader, endData);
        //mConnectionManager.sendData(data);
        System.out.println("发送"+Arrays.toString(data));
        //System.out.println("长度=="+1+"包数"+data.length);
        // System.out.println(Arrays.toString(data));
       // boolean sendSuccess = mConnectionManager.sendData(data);
        //System.out.println("发送成功？"+sendSuccess);
        // }
        //}
    }

    //一个继承自ContentObserver的监听器类
    class SmsObserver extends ContentObserver{

        public SmsObserver(Handler handler) {
            super(handler);
            // TODO Auto-generated constructor stub
        }
        @Override
        public void onChange(boolean selfChange) {
            System.out.println("onchange-----------------------------------------------");
            // TODO Auto-generated method stub
            //查询发送向箱中的短信
            Cursor cursor= context.getContentResolver().query(Uri.parse(
                    "content://sms/outbox"), null, null, null, null);
            //遍历查询结果获取用户正在发送的短信
            while (cursor.moveToNext()) {
                StringBuffer sb=new StringBuffer();
                //获取短信的发送地址
                sb.append("发送地址："+cursor.getString(cursor.getColumnIndex("address")));
                //获取短信的标题
                sb.append("\n标题："+cursor.getString(cursor.getColumnIndex("subject")));
                //获取短信的内容
                sb.append("\n内容："+cursor.getString(cursor.getColumnIndex("body")));
                //获取短信的发送时间
                Date date=new Date(cursor.getLong(cursor.getColumnIndex("date")));
                //格式化以秒为单位的日期
                SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日 hh时mm分ss秒");
                sb.append("\n时间："+sdf.format(date));
                System.out.println("查询到的正在发送的短信："+sb.toString());
            }
            super.onChange(selfChange);
        }

    }
}
